import { Op } from 'sequelize';
import BaseController from './base';
import AppParameterValues from '../models/app-parameter-values';
import AppParameterNames from '../models/app-parameter-name';

// order docs https://sequelize.org/docs/v6/core-concepts/model-querying-basics/
class AppParameterValueController extends BaseController {
  getModel() {
    return AppParameterValues;
  }

  getFindWhere(req) {
    const { name } = req.user;
    const { hotel_id, user_type } = req.user;
    const where = {
      hotel_id
    };

    if (user_type === 'Customer') {
      where.level = 'Hotel';
    }

    if (name) {
      where[Op.or] = [
        { name: { [Op.like]: `%${name}%` } },
        { description: { [Op.like]: `%${name}%` } }
      ];
    }

    return { where };
  }

  getInclude(req) {
    return {
      include: [{
        model: AppParameterNames,
        as: 'app_parameter_name',
        required: true
      }]
    };
  }

  async findOne(req, res, next) {
    try {
      const { id } = req.params;
      const model = this.getModel();
      const data = await model.findOne({
        where: { id },
        include: [{
          model: AppParameterNames,
          as: 'app_parameter_name'
        }],
        rejectOnEmpty: new Error('数据不存在')
      });

      res.sendOk(data);
    }
    catch (e) {
      next(e);
    }
  }
}

export default new AppParameterValueController();
